

hex2bin <- function (data) {
  bin <- apply(outer(0:15, 3:0,
                     function(x,y)x %/% (2^y) %% 2),
                     1, paste, collapse="")
  names(bin) <- format.hexmode(0:15)
  return(sapply(strsplit(data,'') , function(x) paste(bin[x], collapse='')))
}


bin2dec <- function(x) {
  x <- as.numeric(unlist(strsplit(x, ""))) 
  return (sum(x * 2^(rev(seq_along(x)) - 1)))
}


extractTemperature <- function(code)  {
  temperature <- NA
  
  binary <- hex2bin(code)
  message <- bin2dec(substr(binary, 0 ,3))
  
  if (message == 0) {
    voltage <- bin2dec(substr(binary, 4, 7)) * 0.064 + 2.704
    txCount <- bin2dec(substr(binary, 8, 12)) * 128
    tmp <- bin2dec(substr(binary, 13, 21))
    temperature <- (0.00000015762 * (tmp^3)) - (0.0001034 * (tmp^2)) + (0.1213*tmp) - 10.045
  }
  return (temperature)
}


